package com.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import com.model.MyPermission;

@Service
public class MyInvocationSecurityMetadataSourceService  implements
        FilterInvocationSecurityMetadataSource {

    private HashMap<String, Collection<ConfigAttribute>> authMap =null;

    //加载权限表中所有权限
    public void loadAllPermission(){
        authMap = new HashMap<>();
        List<MyPermission> permissionList = new ArrayList<MyPermission>();
        
        //这里模拟，数据库里取
        permissionList.add(new MyPermission("admin","welcome.jsp"));
        
        for(MyPermission permission : permissionList) {
        	
        	String url = permission.getUrl();
        	String permissionName = permission.getName();
            ConfigAttribute permissionConfig = new SecurityConfig(permissionName);
        	
        	if(authMap.containsKey(url)){
        		authMap.get(url).add(permissionConfig);
            }else{
            	List<ConfigAttribute> configList = new ArrayList<ConfigAttribute>();
            	configList.add(permissionConfig);
            	authMap.put(url,configList);
            }
        }

    }

//此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给 decide 方法，用来判定用户是否有此权限。如果不在权限表中则放行。
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if(authMap ==null){
        	loadAllPermission();
        }

        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        AntPathRequestMatcher matcher;         
        for(Iterator<String> iter = authMap.keySet().iterator(); iter.hasNext(); ) {        	
            matcher = new AntPathRequestMatcher(iter.next());
            if(matcher.matches(request)) {
                return authMap.get(iter.next());
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}